import { app, BrowserWindow, dialog, ipcMain, Menu, MenuItem } from 'electron'
import * as path from 'path'
import * as url from 'url'
import installExtension, { REACT_DEVELOPER_TOOLS, REDUX_DEVTOOLS } from 'electron-devtools-installer'
import { AppMenu } from './menu'
import fs from 'fs'

const isMac = process.platform === 'darwin'
const debug = /--debug/.test(process.argv[2])

const ElectronApp = {
  mainWindow: null! as Electron.BrowserWindow,
  // devWindow: null as Electron.BrowserWindow,
  appMenu: null! as AppMenu,

  /**
     * 初始化 Electron App
     */
  init () {
    app.on('ready', () => this.onReady())
    // prevent app from exiting at first request: the user may attempt to exit the app
    // while transfers are in progress so we first send a request to the frontend
    // if no transfers are in progress, exit confirmation is received which makes the app close
    // app.on('before-quit', (e) => {
    //     // TODO: detect interrupt
    //     console.log('before quit');
    //     if (!this.forceExit) {
    //         console.log('no forceExit, sending exitRequest to renderer');
    //         e.preventDefault();
    //         this.mainWindow.webContents.send('exitRequest');
    //     } else {
    //         console.log('forceExit is true, calling cleanupAndExit');
    //         this.cleanupAndExit();
    //     }
    // });

    app.on('activate', (e) => {
      if (this.mainWindow) {
        this.mainWindow.restore()
      }
    })

    // 全部关闭
    app.on('window-all-closed', function () {
      if (!isMac) {
        console.log('已经退出')
        app.quit()
      }
    })

    app.allowRendererProcessReuse = true

    // when interrupt is received we have to force exit
    // process.on('SIGINT', function () {
    //     console.log('*** BREAK');
    //     this.forceExit = true;
    // });
  },

  onReady () {
    console.log('App Ready')
    // react-devtools doesn't work properly with file:// scheme, starting with Electron 9
    // see: https://github.com/electron/electron/issues/24011 &
    // https://github.com/electron/electron/pull/25151
    // if (!ENV_E2E && !isPackage) {
    //     this.installReactDevTools();
    // }

    if (process.env.NODE_ENV === 'development') {
      installExtension(REACT_DEVELOPER_TOOLS)
        .then((name) => console.log(`Added Extension:  ${name}`))
        .catch((err) => console.log('An error occurred: ', err))
      installExtension(REDUX_DEVTOOLS)
        .then((name) => console.log(`Added Extension:  ${name}`))
        .catch((err) => console.log('An error occurred: ', err))
    }
    this.installIpcMainListeners()
    this.createMainWindow()
    // this.openDevTools();
  },

  /**
     *
     */
  installIpcMainListeners () {
    ipcMain.on('project-route', (event, number) => {
      this.appMenu.assignRoute()
    })

    ipcMain.on('on-save', (event, number) => {
      console.log(number)
    })

    ipcMain.on('create-data', (event, number) => {
      console.log(number)
    })

    ipcMain.on('delete-data', (event, number) => {
      console.log(number)
    })

    ipcMain.handle('readFile', (event, path, options) => {
      return fs.promises.readFile(path, options)
    })

    ipcMain.handle('readdir', (event, path, options) => {
      return fs.promises.readdir(path, options)
    })

    ipcMain.handle('writeFile', (event, file, data, options) => {
      return fs.promises.writeFile(file, data, options)
    })

  },

  createMainWindow () {
    this.mainWindow = new BrowserWindow({
      width: 1100,
      height: 700,
      backgroundColor: '#191622',
      // frame: false,
      icon: path.join(__dirname, '../src/assets/images/CPU-pixel.png'),
      webPreferences: {
        nodeIntegration: true,
        enableRemoteModule: true
      }
    })

    if (process.env.NODE_ENV === 'development') {
      this.mainWindow.loadURL('http://localhost:4000')
    } else {
      this.mainWindow.loadURL(
        url.format({
          pathname: path.join(__dirname, 'renderer/index.html'),
          protocol: 'file:',
          slashes: true
        })
      )
    }

    this.mainWindow.webContents.openDevTools()
    this.mainWindow.maximize()
    // 在打开 DevTools 的情况下全屏启动, 用法: npm run debug
    // if (debug) {
      
    // }
    // 最小化
    this.mainWindow.on('minimize', () => {
      this.mainWindow.minimize()
    })

    this.mainWindow.on('closed', () => {
      this.mainWindow = null!
    })

    // macOS: 如果没有窗口打开一个
    app.on('activate', () => {
      if (BrowserWindow.getAllWindows().length === 0) this.createMainWindow()
    })

    this.appMenu = new AppMenu(this.mainWindow)
    this.appMenu.createMenu()
  }

}

/**
 * 事件列表
 */
ElectronApp.init()
